package com.sync.syncmasterdata.product.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sync.syncmasterdata.configuration.ConfInfo;
import com.sync.syncmasterdata.customer.service.http.HttpAPIServiceForCrmSync;
import com.sync.syncmasterdata.dingrobot.service.DingRobotService;
import com.sync.syncmasterdata.product.entity.oa.ProductWorkflowDeleteEntity;
import com.sync.syncmasterdata.product.entity.oa.ProductWorkflowEntity;
import com.sync.syncmasterdata.product.entity.oa.ProductWorkflowUpdateEntity;
import com.sync.syncmasterdata.product.entity.u8.InvEx;
import com.sync.syncmasterdata.product.entity.u8.InvFreeContrapose;
import com.sync.syncmasterdata.product.entity.u8.Inventory;
import com.sync.syncmasterdata.product.entity.wms.EleProduct;
import com.sync.syncmasterdata.product.pojo.cp.InventoryForCP;
import com.sync.syncmasterdata.product.pojo.crm.InventoryForCrm;
import com.sync.syncmasterdata.product.pojo.crm.ResponseInventoryForCrm;
import com.sync.syncmasterdata.product.pojo.erp.InventoryForU8;
import com.sync.syncmasterdata.product.pojo.gsp.InventoryForGsp;
import com.sync.syncmasterdata.product.pojo.oa.InventoryForOA;
import com.sync.syncmasterdata.product.repository.oa.InventoryForDeleteWorkflowRepository;
import com.sync.syncmasterdata.product.repository.oa.InventoryForUpdateWorkflowRepository;
import com.sync.syncmasterdata.product.repository.oa.InventoryWorkflowRepository;
import com.sync.syncmasterdata.product.repository.oa.UpdateChanpinbmRepository;
import com.sync.syncmasterdata.product.repository.u8.ComputationunitRepository;
import com.sync.syncmasterdata.product.repository.u8.InvExRepository;
import com.sync.syncmasterdata.product.repository.u8.InvFreeContraposeRepository;
import com.sync.syncmasterdata.product.repository.u8.InventoryRepository;
import com.sync.syncmasterdata.product.service.convert.ProductU8toCP;
import com.sync.syncmasterdata.product.service.convert.ProductU8toCRM;
import com.sync.syncmasterdata.util.AuthUtil;
import com.sync.syncmasterdata.util.NormalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.transaction.Transactional;
import java.nio.charset.StandardCharsets;
import java.text.DecimalFormat;
import java.util.*;

import static com.sync.syncmasterdata.util.NormalUtil.getNowDataTime;

/**
 * 手动 处理业务的相关服务
 */
@Transactional
@Service
@Slf4j
public class ManualSyncInventoryService {

    @Autowired
    private HttpAPIServiceForCrmSync httpAPIService;

    @Autowired
    private InventoryRepository inventoryRepository;
    @Autowired
    private InvFreeContraposeRepository invFreeContraposeRepository;

    @Autowired
    private InventoryWorkflowRepository inventoryWorkflowRepository;

    @Autowired
    private InventoryForUpdateWorkflowRepository inventoryForUpdateWorkflowRepository;
    @Autowired
    private InventoryForDeleteWorkflowRepository inventoryForDeleteWorkflowRepository;
    @Autowired
    private UpdateChanpinbmRepository updateChanpinbmRepository;

    @Autowired
    private ComputationunitRepository computationunitRepository;

    @Autowired
    private InvExRepository invExRepository;

//    @Autowired
//    private ProductForWmsRepository productForWmsRepository;

    @Autowired
    private ConfInfo confInfo;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AuthUtil authUtil;
    @Autowired
    private DingRobotService dingRobotService;

    @Autowired
    private ProductU8toCRM productU8toCRM;
    @Autowired
    private ProductU8toCP productU8toCP;


    private static final String crmEntity = "new_products";
    @Value("${myprops.cpurl}")
    private String CPURL;
    private static String[] SUSER = {"15267167276"};

    /**
     * U8 openapi用 静态变量(配套 新增、更新用) @Value("${maycur.url}")
     */
    private final String FROM_ACCOUNT = "biosanu8";
    private final String TO_ACCOUNT = "biosanu8";
    @Value("${ukey.product_key}")
    private String PRODUCT_APP_KEY;
    @Value("${ukey.product_secret}")
    private String PRODUCT_APP_SECRET;

    @Value("${gsp.url}")
    private String GSPURL;

    /**
     * 处理bpm的产品缺少问题
     * @param code
     * @return
     */
    public String handlerProductErpHas(String code) {
        StringBuilder sb = new StringBuilder();
        Inventory inventory = inventoryRepository.hasProductByCode(code);
        if (Objects.isNull(inventory)) {
            return "ERP不存在该产品，请走OA的产品新增流程";
        }
        //获取u8产品对象
        InventoryForU8 u8entity = getProductFromERP(code,"2");

        //转crm对象
        //确定crm是否存在
        String crmHasProduct = getProductFromCrmHas(code);
        if(StringUtils.isBlank(crmHasProduct)){
            //不存在新增
            InventoryForCrm crmEntity = productU8toCRM.convertTo(u8entity);
            crmHasProduct=addInvToCrm(crmEntity);
            if(StringUtils.isBlank(crmHasProduct)){
                sb.append("CRM新增失败,");
                log.info("CRM新增失败");
                dingRobotService.simpleDingSendMsg("手动同步新增失败",SUSER);
            }else{
                sb.append("CRM新增成功,");
            }
        }else{
            sb.append("CRM已经存在（不做处理）,");
        }
        //确定wms是否存在

        //确定业务中台是否存在
        if(!getProductFromCP(code)){
            //如果不存在 新增
            InventoryForCP cpEntity = productU8toCP.convertTo(u8entity);
            cpEntity.setCrmid(crmHasProduct);
            cpEntity.setErpid(code);
            //todo:要先部署cp的接口
            String oid=addInvToCP(cpEntity);
            sb.append("BPM新增档案完成");
        }else{
            sb.append("BPM中台已经存在");
        }

        return sb.toString();
    }

    /**
     * 通过erp 接口获取  产品数据
     * @param code
     * @return
     */
    private InventoryForU8 getProductFromERP(String code,String ds_s) {
        String token = authUtil.getCPTokenByTag("u8prosync");
        //获取可以固定数据源
        String requestUrl = confInfo.getU8opeapiurl() + "api/inventory/get?from_account=" + FROM_ACCOUNT + "&to_account=" + TO_ACCOUNT + "&app_key=" + PRODUCT_APP_KEY + "&token=" + token + "&id=" + code+"&ds_sequence="+ds_s;

        try {
            String ret = httpAPIService.doGet(requestUrl);
            JSONObject retJson = new JSONObject(ret);
            if(retJson.get("errcode").equals("0")){
                //调用成功
                InventoryForU8 u8entity = objectMapper.readValue(retJson.getString("inventory"), InventoryForU8.class);
                return u8entity;
            }else{
                log.info("通过API获取U8产品对象返回为空");
                return null;
            }

        } catch (Exception e) {
            log.info("通过API获取U8产品对象异常");
            return null;
        }

    }

    //crm是否存在产品
    private String getProductFromCrmHas(String  code) {
        String requestUrl = String.format("%s%s?%s", this.confInfo.getCrmurl(), "new_products", "$filter=new_code eq '" + code + "'");

        try {
            String responseStr = httpAPIService.doGetCrm(requestUrl);
            JSONObject jsonObject = new JSONObject(responseStr);
            JSONArray jsonArray = jsonObject.getJSONArray("value");
            if (jsonArray.length() == 0) {
                return null;
            }else{
                JSONObject obj=(JSONObject) jsonArray.get(0);
                return obj.getString("new_productid");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
    private String addInvToCrm(InventoryForCrm inventoryForCrm) {
        String requestUrl = String.format("%s%s", this.confInfo.getCrmurl(), crmEntity);

        try {
            log.info("Crm新增待请求字符串:" + objectMapper.writeValueAsString(inventoryForCrm));
            String responseStr = httpAPIService.doPostCrm(requestUrl, objectMapper.writeValueAsString(inventoryForCrm));

            ResponseInventoryForCrm responseInventoryForCrm = objectMapper.readValue(responseStr, ResponseInventoryForCrm.class);
            String new_productid = responseInventoryForCrm.getNew_erp_productid();
            if (new_productid != null) {
                return new_productid;
            } else {
                //失败
                log.info("Crm请求返回：{}", objectMapper.writeValueAsString(responseInventoryForCrm));
                return null;
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }

    }

    /**
     * 确认cp 是否有该产品
     * @param code
     * @return
     */
    private boolean getProductFromCP(String code) {
        String requestUrl = String.format("%s%s", this.CPURL, "/api/outservice/getProductByProductCode?code="+code);
        String oid = "";
        try {
            oid = httpAPIService.doGet(requestUrl);
            if (StringUtils.isNotBlank(oid)) {
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }

    }

    /**
     * 新增中台 存货档案
     *
     * @return
     */
    public String addInvToCP(InventoryForCP cp) {
        String requestUrl = String.format("%s%s", this.CPURL, "/api/outservice/addProduct");
        String oid = "";
        try {
            System.out.println("请求cp报文打印："+objectMapper.writeValueAsString(cp));
            oid = httpAPIService.doPost(requestUrl, objectMapper.writeValueAsString(cp));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return oid;

    }
}
